package org.abratuhi.kvngroupware.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import org.abratuhi.kvngroupware.client.KVNGroupwareClient;
import org.abratuhi.kvngroupware.gui.GUIChatroom;
import org.abratuhi.kvngroupware.model.Chatroom;
import org.abratuhi.kvngroupware.network.Message;
import org.jdom.Element;

public class ChatroomController implements ActionListener, WindowListener{
	
	Chatroom chatroom;
	KVNGroupwareClient kvnclient;
	GUIChatroom guichatroom;
	
	public ChatroomController(KVNGroupwareClient kvnclient, GUIChatroom guichatroom, Chatroom chatroom){
		this.kvnclient = kvnclient;
		this.guichatroom = guichatroom;
		this.chatroom = chatroom;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource().equals(guichatroom.buttonSend)){
			String[] attrNames = new String[]{"type", "action", "chatroomId", "userId"};
			String[] attrValues= new String[]{"chatroom", "send", chatroom.getId(), kvnclient.getUser().getId()};
			String text = guichatroom.textareaMessage.getText();
			Element[] content = new Element[0];
			
			Message message = kvnclient.createMessage(attrNames, attrValues, text, content);
			kvnclient.sendMessage(message);
			
			guichatroom.textareaMessage.setText("");
		}
	}

	@Override
	public void windowActivated(WindowEvent e) {}

	@Override
	public void windowClosed(WindowEvent e) {}

	@Override
	public void windowClosing(WindowEvent e) {
		String[] attrNames = new String[]{"type", "action", "chatroomId", "userId"};
		String[] attrValues= new String[]{"chatroom", "leave", chatroom.getId(), kvnclient.getUser().getId()};
		String text = new String();
		Element[] content = new Element[0];
		
		Message message = kvnclient.createMessage(attrNames, attrValues, text, content);
		kvnclient.sendMessage(message);
	}

	@Override
	public void windowDeactivated(WindowEvent e) {}

	@Override
	public void windowDeiconified(WindowEvent e) {}

	@Override
	public void windowIconified(WindowEvent e) {}

	@Override
	public void windowOpened(WindowEvent e) {}

}
